'use strict';
const db = uniCloud.database()
const dbCmd = db.command
// function formatUrl(data){
// 	data.map(v=>{
// 		v.imgUrl = uniCloud.getTempFileURL(v.imgUrl)
// 	})
// }
function getField(field){
	let empty={};
	let arr = field.split(',');
	arr.map(v=>empty[v]=true)
	return empty;
}
exports.main = async (event, context) => {
	const collection = db.collection('product')
	const name = event.name;
	const by = event.by || "asc";
	const filter = {
		name:{
			$regex:'.*'+ name,
			$options: 'i'
		}
	}
	
	const pageIndex = event.pageIndex ? event.pageIndex : 1 ;  //当前第几页，默认为第一页
	const pageSize = event.pageSize ? event.pageSize : 5 ;  //每页取多少条记录，默认为10条
	const countResult = await collection.where(filter).count()  //获取集合中的总记录数
	const total = countResult.total  //得到总记录数 
	const totalPage = Math.ceil(total / pageSize)  //计算页数
	let hasMore;
	if(pageIndex * pageSize >= total){
		hasMore = false
	}else{
		hasMore = true
	}
	
	let res = await collection.field(getField("imgUrl,name,price"))
	.where(filter)
	.skip((pageIndex - 1) * pageSize)
	.limit(pageSize)
	.orderBy("price",by)
	.get()
	res.total = total
	res.hasMore = hasMore
	return res // 返回json给客户端
};
